import Taro from "@tarojs/taro";
export const isDev = () => {
  return process.env.NODE_ENV === "development";
};

/**
 * 页面跳转
 * @param url
 */
export const goToPage = (url: string) => {
  console.log(url);
  // TODO: 需要支持 tabbar
  Taro.navigateTo({
    url: url,
  });
};

export const PAGE_WEBVIEW = "/pages/webview/webview";

/**
 * 获取胶囊按钮位置信息
 * @returns
 */
export const getMenuButtonBoundingClientRectCompat = () => {
  if (process.env.TARO_ENV === "weapp") {
    return Taro.getMenuButtonBoundingClientRect();
  }
  // 对于 H5 或其他环境，返回一个默认对象或者根据设计调整
  return {
    // 提供一些默认值或者模拟的值
    top: 0,
    right: 0,
    bottom: 0,
    left: 0,
    width: 0,
    height: 0,
  };
};

interface ChooseImage {
  count?: number; // 默认为9, 设置图片的数量
  sizeType?: Array<"original" | "compressed">; // 可以指定是原图还是压缩图，默认二者都有
  sourceType?: Array<"album" | "camera">; // 可以指定来源是相册还是相机，默认二者都有
}

/**
 * 选取图片
 * @param options
 */
export const chooseImage = async (options?: ChooseImage) => {
  let tempFiles: any[] = [];
  await Taro.chooseImage({
    ...options,
    success: (res) => {
      // 返回图片文件列表
      tempFiles = res?.tempFiles || [];
    },
    fail: (res) => {
      // 返回图片文件列表
      tempFiles = [];
    },
  });
  return tempFiles;
};

export const getRandomString = (length = 10): string => {
  let result = "";
  let characters =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  let charactersLength = characters.length;
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }
  return result;
};

export const urlStringify = (url, payload, encode = true) => {
  const arr = Object.keys(payload).map(
    (key) =>
      `${key}=${encode ? encodeURIComponent(payload[key]) : payload[key]}`
  );

  // NOTE 注意支付宝小程序跳转链接如果没有参数，就不要带上 ?，否则可能无法跳转
  return arr.length ? `${url}?${arr.join("&")}` : url;
};

export const toLogin = async (path = "") => {
  const payload = {
    redirect_uri: `${process.env.TARO_APP_DEFAULT_REDIRECT_ORGIN_PREFIX}/#${
      path || process.env.TARO_APP_DEFAULT_REDIRECT_URI
    }?platform=feishu`,
    app_id: process.env.TARO_APP_APP_ID,
  };

  console.log("payload", payload);
  let viewUrl = urlStringify(process.env.TARO_APP_DEFAULT_LOGIN_URI, payload);
  let targetUrl = urlStringify(PAGE_WEBVIEW, { url: viewUrl });
  console.log("viewUrl1", viewUrl);
  console.log("targetUrl", targetUrl);
  Taro.navigateTo({
    url: targetUrl,
  });
};

export const toSuccessTransferHome = async (
  params: ISuccessTransferPageProps
) => {
  const base_url = "pages/transferHome/success/index";
  const cParams = {
    title: "操作成功",
    backPageName: "",
    backUrl: "",
    btnTitle: "返回",
    delay: 5,
    ...params,
  };
  let targetUrl = urlStringify(base_url, cParams);

  goToPage(targetUrl);
};
